#!/usr/bin/env python

import paramiko


class  Auto_ssh:
    def trans(self,hostname,port,username,password,local_dir,remote_dir):
        try:
            sshcon=paramiko.Transport((hostname,port))
            sshcon.connect(username=username,password=password)
            sftp = paramiko.SFTPClient.from_transport(sshcon)
            files = os.listdir(local_dir)
            for f in files:
                    sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))
            t.close()
        except:   
            print "%s connect error!" %(hostname)


    def execute_key(self,hostname,user,cmd):
        pkey='/root/.ssh/id_rsa'
        sshcon = paramiko.SSHClient()  # will create the object
        sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())# no known_hosts error
        sshcon.connect(hostname, username=user, key_filename=pkey) # no passwd needed
        stdin,stdout,stderr=sshcon.exec_command(cmd,timeout=10)  
        return stdout.read()
        #return stdout.readlines()
        sshcon.close()

    def execute_passwd(self,hostname,port,user,password,cmd):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname,port=port,username=user,password=password)
        stdin, stdout, stderr = ssh.exec_command(cmd)
        return stdout.readlines()
        ssh.close()
